package com.hyj.util;



import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

public class JsonUtil {
	private static ObjectMapper m = new ObjectMapper();
    private static JsonFactory jf = new JsonFactory();
    
    static{
    	//支持单引号
    	m.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        //    m.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, false);
        m.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);  
    
    // 日期格式化
       SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");   
      //  m.getSerializationConfig().setDateFormat(formatter); 
        m.getSerializationConfig().withDateFormat(formatter);
    }
    
    /**
     * json 字符串转换成java
     * @param <T>
     * @param jsonAsString
     * @param pojoClass
     * @return
     * @throws JsonMappingException
     * @throws JsonParseException
     * @throws IOException
     */
    public static <T> T fromJson(String jsonAsString, Class<T> pojoClass)
    throws JsonMappingException, JsonParseException, IOException {
    	
        return m.readValue(jsonAsString, pojoClass);
    }
    
    public static String toJson(Object pojo, boolean prettyPrint)
    throws JsonMappingException, JsonGenerationException, IOException {
        StringWriter sw = new StringWriter();
        JsonGenerator jg = jf.createJsonGenerator(sw);
        if (prettyPrint) {
            jg.useDefaultPrettyPrinter();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");   
        m.getSerializationConfig().setDateFormat(formatter); 
        m.getSerializationConfig().withDateFormat(formatter);
        m.writeValue(jg, pojo);
        return sw.toString();
    }
    
    
    public static <T>  T getParam(String key,Map<?,?> m,Class<T> c){
    	Object o  = m.get(key);
    	if(o!=null && c.isInstance(o)){
    		 return (T)o;
    	}
    	return null;
    }

}
